package top.chendawei.system.web.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import top.chendawei.main.facade.UserFacadeImpl;
import top.chendawei.system.beans.vo.param.PageCriteria;
import top.chendawei.util.JsonResult;
import top.chendawei.util.fastjson.FastJsonUtil;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public abstract class AbstractBaseController {
    @Autowired
    private UserFacadeImpl userFacade;

    @Autowired
    private HttpSession httpSession;

    protected void outError(String msg, HttpServletResponse response)
            throws Exception {
        JsonResult<Object> json = new JsonResult();
        json.setSuccess(false);
        json.setMessage(msg);
        outJson(json, response);
    }

    protected void outSuccess(HttpServletResponse response)
            throws Exception {
        JsonResult<Object> json = new JsonResult();
        outJson(json, response);
    }

    protected void outString(String obj, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(obj);
        response.getWriter().flush();
    }

    public void outJson(Object obj, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        String json = FastJsonUtil.toJSONString(obj);

        response.getWriter().println(json);
        response.getWriter().flush();
    }

    public String getJson(Object obj) {
        String json = FastJsonUtil.toJSONString(obj);
        return json;
    }


    public void initPageParam(PageCriteria param) {
        if (null == param) {
            param = new PageCriteria();
        }
        if (null == param.getCurrent() || null == param.getPageSize()) {
            param.setPageSize(20);
            param.setCurrent(1);
        }
        if (StringUtils.isNoneBlank(param.getAscs())) {
            param.setOrderBy(param.getAscs());
            param.setOrderType(" asc ");
        } else if (StringUtils.isNoneBlank(param.getDescs())) {
            param.setOrderBy(param.getDescs());
            param.setOrderType(" desc ");
        }
    }

}
